let editIndex = undefined;
let table = $("#" + datalist);

function endEditing(){
    if (editIndex === undefined){
        return true;
    }
    if (table.datagrid("validateRow", editIndex)){
        let editor = table.datagrid("getEditor", {
            index: editIndex,
            field: "productId"
        });

        table.datagrid("getRows")[editIndex]["name"] = $(editor.target).combobox("getText");
        table.datagrid("endEdit", editIndex);
        
        editIndex = undefined;
        
        return true;
    } else {
        return false;
    }
}

function onClickRow(index){
    if (editIndex !== index){
        if (endEditing()){
            table.datagrid("selectRow", index).datagrid("beginEdit", index);
            
            editIndex = index;
        } else {
            table.datagrid("selectRow", editIndex);
        }
    }
}

function append() {
    if (endEditing()) {
        table.datagrid("appendRow",{
            status: "P"
        });
        editIndex = table.datagrid("getRows").length - 1;
        table.datagrid("selectRow", editIndex).datagrid("beginEdit", editIndex);
    }
}

function remove() {
    if (editIndex === undefined){
        return;
    }
    table.datagrid("cancelEdit", editIndex).datagrid("deleteRow", editIndex);
    
    editIndex = undefined;
}

function accept() {
    if (endEditing()){
        table.datagrid("acceptChanges");
    }
}

function reject() {
    table.datagrid("rejectChanges");
    
    editIndex = undefined;
}

function getChanges() {
    let rows = table.datagrid("getChanges");
    
    alert(rows.length + " rows are changed!");
}